<!--
 * 遮罩层
 * @作者: 陈老师儿~
 * @手机: 18560000860
 -->
<template>
    <view class="pure-overlay" :class="classes" :style="styles" @tap="handleClick" @transitionend="handleTransitionEnd">
        <slot></slot>
    </view>
</template>

<script>
    import props from "./props.js";
    export default {
        options: {
            // 将自定义节点设置成虚拟的
            // 头条、飞书：因为合并后丢失事件和 'provide/inject'
            // 京东：因为合并后不能合并外层 'class'
            // 百度：因为合并后会在控制台疯狂报警告
            // #ifndef MP-TOUTIAO || MP-LARK || MP-JD || MP-BAIDU
            virtualHost: true,
            // #endif

            // 组件样式隔离
            styleIsolation: "apply-shared",

            // 允许使用多个插槽
            multipleSlots: true,
        },
        props: props,
        emits: ["close"],
        data() {
            return {
                // 显示状态
                status: "hide",
            };
        },
        computed: {
            // classes
            classes() {
                const classes = [];

                // 显示状态类名
                classes.push(`pure-overlay-${this.status}`);

                return classes;
            },

            // styles
            styles() {
                const styles = [];
                return styles;
            },
        },
        watch: {
            // 监听显示状态
            show: {
                async handler(val) {
                    // 设置对应的状态类名
                    if (val) {
                        this.status = "before-show";
                        await this.$nextTick();
                        await this.sleep(20);
                        this.status = "to-show";
                    } else {
                        this.status = "before-hide";
                        await this.$nextTick();
                        await this.sleep(20);
                        this.status = "to-hide";
                    }
                },
            },
        },
        mounted() {
            // 初始化状态
            this.status = this.show ? "show" : "hide";
        },
        methods: {
            // 遮罩点击事件
            handleClick() {
                this.$emit("close");
            },

            // 过渡结束事件
            handleTransitionEnd() {
                // 更新状态
                if (this.status === "to-show") {
                    this.status = "show";
                    return;
                }
                if (this.status === "to-hide") {
                    this.status = "hide";
                    return;
                }
            },
            // Sleep
            sleep(time = 10) {
                return new Promise((resolve) => {
                    let timer = setTimeout(() => {
                        clearTimeout(timer);
                        resolve();
                    }, time);
                });
            },
        },
    };
</script>

<style scoped>
    @import "./style.css";
</style>
